Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

266
Vistas
[JavaScript]Add elements to a global array in a function and keep them

window.onload = function(){
    func1();
};

var list = [];

function func1(){
  for(var i = 0; i < 9; i++){
    list.push(i);
  }
}

console.log(list);

Which the output log is an empty array, then how do I add elements to a global array in a function, and access them globally?

about 4 years ago · Juan Pablo Isaza
3 Respuestas
Responde la pregunta

0

Your function's code is fine.

However, you are logging the array using console.log before func1() gets to run, since window.onload fires AFTER everything has loaded.

about 4 years ago · Juan Pablo Isaza Denunciar

0

Let's focus on why the console.log in the end is empty.

Note that :

window. onload() is invoked when all resources (the document, objects, images, css, etc) have finished rendering.

So after the console output the list value, if will execute the func1 and assign the value to list, but before that list is just an empty array.

If could see the following snippet, if you put the console to the window.onload function, it works as epected.

You could use push to add item to array and use index to access a specific element.

window.onload = function(){
    func1();
    console.log(list);
    func2()
    console.log(list)
};

var list = [];

function func1(){
  for(var i = 0; i < 9; i++){
    list.push(i);
  }
}
console.log(list);
function func2(){
list[0] =9999

}

about 4 years ago · Juan Pablo Isaza Denunciar

0

You need to wait for the window to load and call your function func1 before logging the value of the array to console...

window.onload = function(){
    func1();
    console.log(list);
};

var list = [];

function func1(){
  for(var i = 0; i < 9; i++){
    list.push(i);
  }
}

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda